package com.csust.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class ReflectionAccessProperties {
    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("com.csust.reflection.Student");
        Constructor<?> constructor = clazz.getConstructor(String.class, int.class);
        Object o = constructor.newInstance("Sail", 19);
        //public 的属性 Age
        Field field = clazz.getField("age");
        field.set(o,22);
        System.out.println(field.get(o));


        //非public 的属性
        Field declaredField = clazz.getDeclaredField("name");
        declaredField.setAccessible(true) ;
//        declaredField.set(o,"yuwen");
        declaredField.set(null,"yuwen996"); //如果是 静态的属性 则也可以使用 null 来代替 传入的实例对象

//        System.out.println(declaredField.get(o));
        System.out.println(declaredField.get(null)); //如果是 静态的属性 则也可以使用 null 来代替 传入的实例对象


    }

}

class Student {
    private static String name;
    public int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
